package com.haifeng.asms.auth.handler;

import cn.hutool.core.bean.BeanUtil;
import com.alibaba.fastjson.JSON;
import com.haifeng.asms.auth.entity.UserDetailsEntity;
import com.haifeng.asms.commons.common.Rest;
import com.haifeng.asms.commons.utils.JsonUtil;
import com.haifeng.asms.dao.model.dto.UserDto;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.web.authentication.SavedRequestAwareAuthenticationSuccessHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * <p>
 * 登录成功处理器
 * </p>
 *
 * @author: Haifeng
 * @date: 2020-06-22
 */
@Slf4j
@Component
public class LoginSuccessHandler extends SavedRequestAwareAuthenticationSuccessHandler {

    /**
     * 业务描述：登录成功返回用户信息
     *
     * @param request
     * @param response
     * @param authentication
     * @return
     */
    @Override
    public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {

        log.info("登录成功:{}",authentication.getPrincipal());
        response.setContentType("application/json;charset=UTF-8");
        User user = (User)authentication.getPrincipal();
        UserDto userDto = JSON.parseObject(user.getUsername(), UserDto.class);
        UserDetailsEntity userDetailsEntity = new UserDetailsEntity();
        BeanUtil.copyProperties(userDto, userDetailsEntity, true);
        Rest rest = Rest.success(userDetailsEntity, "登录成功");
        response.getWriter().write(JsonUtil.toJsonString(rest));
    }
}
